package org.jeecg.modules.zhaojd.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.gudzcdrdygx.entity.HqGudzcDaorsjdygx;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.zhaojd.entity.HqZhaojdDetail;
import org.jeecg.modules.zhaojd.entity.HqZhaojdChif;
import org.jeecg.modules.zhaojd.entity.HqZhaojd;
import org.jeecg.modules.zhaojd.vo.HqZhaojdPage;
import org.jeecg.modules.zhaojd.service.IHqZhaojdService;
import org.jeecg.modules.zhaojd.service.IHqZhaojdDetailService;
import org.jeecg.modules.zhaojd.service.IHqZhaojdChifService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 招接待
 * @Author: jeecg-boot
 * @Date: 2020-10-05
 * @Version: V1.0
 */
@Api(tags = "招接待")
@RestController
@RequestMapping("/zhaojd/hqZhaojd")
@Slf4j
public class HqZhaojdController {
    @Autowired
    private IHqZhaojdService hqZhaojdService;
    @Autowired
    private IHqZhaojdDetailService hqZhaojdDetailService;
    @Autowired
    private IHqZhaojdChifService hqZhaojdChifService;
    @Autowired
    private ISysDepartService sysDepartService;

    @AutoLog(value = "任务审批")
    @ApiOperation(value = "任务审批", notes = "任务审批")
    @PostMapping(value = "/completetask")
    public Result<?> completeTask(@RequestBody Map params) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqZhaojdService.complateTask(loginUser, (String) params.get("taskId"), (String) params.get("processInstanceId"),
                (Integer) params.get("auditStatus"), (String) params.get("auditMemo"));

        return Result.ok("操作成功");
    }

    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(HqZhaojd hqZhaojd,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {

        Page<HqZhaojd> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqZhaojd> iPage = hqZhaojdService.myApplyList(page, user, hqZhaojd);
        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getShenqdw());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setShenqdw_fullName(fullName);
        });
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(HqZhaojd hqZhaojd,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqZhaojd> page = new Page<HqZhaojd>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqZhaojd> iPage = hqZhaojdService.myTodoTasks(page, user, hqZhaojd);
        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getShenqdw());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setShenqdw_fullName(fullName);
        });
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
            });
        }
        return Result.ok(iPage);
    }

    @AutoLog(value = "我的已办-分页列表查询")
    @ApiOperation(value = "我的已办-分页列表查询", notes = "我的已办-分页列表查询")
    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(HqZhaojd hqZhaojd,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqZhaojd> page = new Page<HqZhaojd>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<HqZhaojd> iPage = hqZhaojdService.myDoneTasks(page, user, hqZhaojd);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                }
            });
        }
        iPage.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getShenqdw());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setShenqdw_fullName(fullName);
        });
        return Result.ok(page);
    }
    String dig_parentId(String parentId) {
        SysDepart sysDepart = sysDepartService.getById(parentId);
        // 不显示根节点
        if(sysDepart != null ) {
            return dig_parentId(sysDepart.getParentId()) + "-" + sysDepart.getDepartName();
        }

        return "";
    }
    /**
     * 分页列表查询
     *
     * @param hqZhaojd
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "招接待-分页列表查询")
    @ApiOperation(value = "招接待-分页列表查询", notes = "招接待-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HqZhaojd hqZhaojd,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HqZhaojd> queryWrapper = QueryGenerator.initQueryWrapper(hqZhaojd, req.getParameterMap());
        Page<HqZhaojd> page = new Page<HqZhaojd>(pageNo, pageSize);
        IPage<HqZhaojd> pageList = hqZhaojdService.page(page, queryWrapper);
        pageList.getRecords().stream().forEach(item -> {
            // 前端显示完整层级的组织机构
            String fullName = this.dig_parentId(item.getShenqdw());
            if(fullName.length() > 1)
                fullName = fullName.substring(1);
            item.setShenqdw_fullName(fullName);
        });
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param hqZhaojdPage
     * @return
     */
    @AutoLog(value = "招接待-添加")
    @ApiOperation(value = "招接待-添加", notes = "招接待-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HqZhaojdPage hqZhaojdPage) {
        HqZhaojd hqZhaojd = new HqZhaojd();
        hqZhaojd.setZidybh("ZJDSQ" + DatePattern.PURE_DATE_FORMAT.format(new Date()) + String.format("%04d", hqZhaojdService.count() + 1));

        BeanUtils.copyProperties(hqZhaojdPage, hqZhaojd);

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        hqZhaojdService.startFlow(user,hqZhaojd, hqZhaojdPage.getHqZhaojdDetailList(), hqZhaojdPage.getHqZhaojdChifList());

        return Result.ok("添加成功！");
    }

    /**
     * 提交进入流程
     *
     * @param hqZhaojdPage
     * @return
     */
    @AutoLog(value = "招接待-提交进入流程")
    @ApiOperation(value = "招接待-提交进入流程", notes = "招接待-提交进入流程")
    @PostMapping(value = "/startFlow")
    public Result<?> startFlow(@RequestBody HqZhaojdPage hqZhaojdPage) {
        HqZhaojd hqZhaojd=hqZhaojdService.getById(hqZhaojdPage.getId());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqZhaojdService.startFlow(user,hqZhaojd, hqZhaojdPage.getHqZhaojdDetailList(), hqZhaojdPage.getHqZhaojdChifList());
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hqZhaojdPage
     * @return
     */
    @AutoLog(value = "招接待-编辑")
    @ApiOperation(value = "招接待-编辑", notes = "招接待-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HqZhaojdPage hqZhaojdPage) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        HqZhaojd hqZhaojdEntity = hqZhaojdService.getById(hqZhaojdPage.getId());
        if (hqZhaojdEntity == null) {
            return Result.error("未找到对应数据");
        }

        hqZhaojdService.applyAgain(hqZhaojdPage,user);
        return Result.ok("操作成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招接待-通过id删除")
    @ApiOperation(value = "招接待-通过id删除", notes = "招接待-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hqZhaojdService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "招接待-批量删除")
    @ApiOperation(value = "招接待-批量删除", notes = "招接待-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hqZhaojdService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招接待-通过id查询")
    @ApiOperation(value = "招接待-通过id查询", notes = "招接待-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HqZhaojd hqZhaojd = hqZhaojdService.getById(id);
        if (hqZhaojd == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(hqZhaojd);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招接待入住详情通过主表ID查询")
    @ApiOperation(value = "招接待入住详情主表ID查询", notes = "招接待入住详情-通主表ID查询")
    @GetMapping(value = "/queryHqZhaojdDetailByMainId")
    public Result<?> queryHqZhaojdDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<HqZhaojdDetail> hqZhaojdDetailList = hqZhaojdDetailService.selectByMainId(id);
        return Result.ok(hqZhaojdDetailList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "招接待就餐详情通过主表ID查询")
    @ApiOperation(value = "招接待就餐详情主表ID查询", notes = "招接待就餐详情-通主表ID查询")
    @GetMapping(value = "/queryHqZhaojdChifByMainId")
    public Result<?> queryHqZhaojdChifListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<HqZhaojdChif> hqZhaojdChifList = hqZhaojdChifService.selectByMainId(id);
        return Result.ok(hqZhaojdChifList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hqZhaojd
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqZhaojd hqZhaojd) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<HqZhaojd> queryWrapper = QueryGenerator.initQueryWrapper(hqZhaojd, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<HqZhaojd> wrapper= queryWrapper.eq("create_by", sysUser.getUsername());
        //Step.2 获取导出数据
        List<HqZhaojd> queryList = hqZhaojdService.list(wrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<HqZhaojd> hqZhaojdList = new ArrayList<HqZhaojd>();
        if (oConvertUtils.isEmpty(selections)) {
            hqZhaojdList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            hqZhaojdList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<HqZhaojdPage> pageList = new ArrayList<HqZhaojdPage>();
        for (HqZhaojd main : hqZhaojdList) {
            HqZhaojdPage vo = new HqZhaojdPage();
            BeanUtils.copyProperties(main, vo);
            List<HqZhaojdDetail> hqZhaojdDetailList = hqZhaojdDetailService.selectByMainId(main.getId());
            vo.setHqZhaojdDetailList(hqZhaojdDetailList);
            List<HqZhaojdChif> hqZhaojdChifList = hqZhaojdChifService.selectByMainId(main.getId());
            vo.setHqZhaojdChifList(hqZhaojdChifList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "招接待列表");
        mv.addObject(NormalExcelConstants.CLASS, HqZhaojdPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("招接待数据", "导出人:" + sysUser.getRealname(), "招接待"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<HqZhaojdPage> list = ExcelImportUtil.importExcel(file.getInputStream(), HqZhaojdPage.class, params);
                for (HqZhaojdPage page : list) {
                    HqZhaojd po = new HqZhaojd();
                    BeanUtils.copyProperties(page, po);
                    hqZhaojdService.saveMain(po, page.getHqZhaojdDetailList(), page.getHqZhaojdChifList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
